/*
 * @Author: dadadaXU 1413107032@qq.com
 * @Date: 2025-01-29 17:08:34
 * @LastEditors: dadadaXU 1413107032@qq.com
 * @LastEditTime: 2025-01-29 17:25:39
 * @FilePath: \LeetCode\21.合并两个有序链表.cpp
 * @Description: 这是默认设置,请设置`customMade`, 打开koroFileHeader查看配置 进行设置: https://github.com/OBKoro1/koro1FileHeader/wiki/%E9%85%8D%E7%BD%AE
 */
/*
 * @lc app=leetcode.cn id=21 lang=cpp
 *
 * [21] 合并两个有序链表
 */

struct ListNode
{
    int val;
    ListNode *next;
    ListNode() : val(0), next(nullptr) {}
    ListNode(int x) : val(x), next(nullptr) {}
    ListNode(int x, ListNode *next) : val(x), next(next) {}
};

// @lc code=start
class Solution
{
public:
    ListNode *mergeTwoLists(ListNode *list1, ListNode *list2)
    {
        ListNode *p1 = list1;
        ListNode *p2 = list2;
        ListNode *list3 = nullptr;
        ListNode *rear = nullptr;
        ListNode *temp = nullptr;

        if (p1 != nullptr && p2 != nullptr)
        {
            if (p1->val < p2->val)
            {
                list3 = p1;
                p1 = p1->next;
            }
            else
            {
                list3 = p2;
                p2 = p2->next;
            }
        }
        else if (p1 != nullptr)
            return list1;
        else if (p2 != nullptr)
            return list2;
        else
            return nullptr;

        rear = list3;
        while (p1 != nullptr && p2 != nullptr)
        {
            if (p1->val < p2->val)
            {
                temp = p1;
                p1 = p1->next;
            }
            else
            {
                temp = p2;
                p2 = p2->next;
            }

            rear->next = temp;
            rear = rear->next;
        }

        if (p1 != nullptr)
            rear->next = p1;
        if (p2 != nullptr)
            rear->next = p2;

        return list3;
    }
};
// @lc code=end
